package com.bobi.tfca.ui.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bobi.tfca.R
import com.bobi.tfca.databinding.ItemArticleBigPicBinding
import com.bobi.tfca.network.response.ArticleResponse
import com.bobi.tfca.ui.mainnavigation.home.culture.CultureFragment
import com.bobi.tfca.util.LogUtil
import com.bumptech.glide.Glide

class ArticleAdapter(val context: CultureFragment, var articleList: ArrayList<ArticleResponse>) :
    RecyclerView.Adapter<ArticleAdapter.ArticleViewHolder>() {

    private var mOnItemClickListener: OnItemClickListener? = null

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }

    fun setOnItemClickListener(onItemClickListener: OnItemClickListener?) {
        mOnItemClickListener = onItemClickListener
    }

    fun setItemList(articleList: ArrayList<ArticleResponse>) {
        this.articleList = articleList
    }

    inner class ArticleViewHolder(private val binding: ItemArticleBigPicBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(article: ArticleResponse) {
            val url = article.outsidePicture
            if (url.isNotBlank() && (!"null".equals(url))) {
                Glide.with(context).load(url).placeholder(R.drawable.defaultbg_h)
                    .into(binding.bigImage)
            } else {
                Glide.with(context).load(R.drawable.defaultbg_h).into(binding.bigImage)
            }
            binding.tvTitle.text = article.title
            binding.bottomInfo.tvTime.text = article.releaseTime
            binding.bottomInfo.tvRight.text = article.likes.toString()
            LogUtil.i("${article.likes.toString()}---------${binding.bottomInfo.tvRight.text}")
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {
        val itemView =
            ItemArticleBigPicBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        val viewHolder = ArticleViewHolder(itemView)
        return viewHolder
    }

    override fun getItemCount(): Int = articleList.size
    override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) {
        val article = articleList[position]

        with(holder) {
            bind(article)
            itemView.setOnClickListener {
                mOnItemClickListener?.onItemClick(position)
            }
        }
    }

}